import sys
import os
import random
from PyQt5 import QtWidgets, QtCore, QtGui, QtNetwork
from wallpaper_ui import Ui_MainWindow
import ctypes
import tempfile
import warnings
import logging

warnings.filterwarnings("ignore", category=DeprecationWarning)

logging.basicConfig(filename='app.log', level=logging.DEBUG)

class WallpaperApp(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.setWindowTitle("Ali Wallpaper")

        # self.setWindowIcon(QtGui.QIcon('icon.ico'))
        
        # 加载样式表
        self.load_stylesheet("style.qss")
        
        # 可用分类列表
        self.categories = {
            self.cb_anime: "anime",
            self.cb_ocean: "ocean",
            self.cb_biglink: "bigLink",
            self.cb_travel: "travel",
            self.cb_food: "food-drink",
            self.cb_nature: "nature",
            self.cb_architecture: "architecture",
            self.cb_animal: "animals",
            self.cb_technology: "technology",
            self.cb_street: "street-photography"
        }

        # 网络管理器
        self.net_manager = QtNetwork.QNetworkAccessManager()
        self.current_image = None
        
        # 添加尺寸复选框映射
        self.size_checks = {
            "小": self.cb_size_small,
            "中": self.cb_size_medium,
            "大": self.cb_size_large,
            "原始": self.cb_size_original
        }

        # 连接信号
        self.get_btn.clicked.connect(self.get_random_wallpaper)
        self.download_btn.clicked.connect(self.download_wallpaper)
        self.set_wallpaper_btn.clicked.connect(self.set_wallpaper)  # 连接新按钮
        self.cb_anime.setChecked(True)  # 默认选择第一个动漫分类
        self.size_combo.setCurrentIndex(2)  # 默认选中大尺寸
        self.size_checks["大"].setChecked(True)
        self.get_random_wallpaper()  # 启动时加载一张随机壁纸
        
    def get_selected_categories(self):
        """获取选中的分类"""
        return [v for cb, v in self.categories.items() if cb.isChecked()]
    
    def get_random_wallpaper(self):
        """获取随机壁纸"""
        selected = self.get_selected_categories()
        if not selected:
            QtWidgets.QMessageBox.warning(self, "提示", "请至少选择一个分类！")
            return
        
        # 保存当前分类和随机码
        self.current_category = random.choice(selected)
        self.current_code = random.randint(0, 10000)
        self.lbl_random_code.setText(f"当前随机码：{self.current_code}")
        
        # 根据选择的尺寸生成参数
        size_choice = self.size_combo.currentText()
        if size_choice == "小":
            size_param = "?imageMogr2/auto-orient/thumbnail/600x/blur/1x0/quality/75"
        elif size_choice == "中":
            size_param = "?imageMogr2/auto-orient/thumbnail/1000x/blur/1x0/quality/75"
        elif size_choice == "大":
            size_param = "?imageMogr2/auto-orient/blur/1x0/quality/71"
        else:  # 原始
            size_param = ""
        
        url = f"https://infinitypro-img.infinitynewtab.com/wallpaper/{self.current_category}/{self.current_code}.jpg{size_param}"
        print(url)
        request = QtNetwork.QNetworkRequest(QtCore.QUrl(url))
        self.reply = self.net_manager.get(request)
        self.reply.finished.connect(self.on_image_loaded)
        self.preview_label.setText("正在加载...")
        
    def on_image_loaded(self):
        """图片加载完成处理（添加重试逻辑）"""
        if self.reply.error():
            self.retry_count = getattr(self, 'retry_count', 0)
            if self.retry_count < 1:
                self.retry_count += 1
                # 生成新随机码重试
                self.current_code = random.randint(0, 10000)
                self.lbl_random_code.setText(f"当前随机码：{self.current_code}（重试中）")
                self.retry_request()
                return
            else:
                self.preview_label.setText("加载失败，请重试")
                self.retry_count = 0
                return
                
        img_data = self.reply.readAll()
        self.current_image = QtGui.QImage()
        if self.current_image.loadFromData(img_data):
            pixmap = QtGui.QPixmap.fromImage(self.current_image)
            self.preview_label.setPixmap(
                pixmap.scaled(
                    self.preview_label.size(),
                    QtCore.Qt.KeepAspectRatio,
                    QtCore.Qt.SmoothTransformation
                )
            )
        else:
            self.preview_label.setText("无效的图片数据")
            
        self.retry_count = 0  # 重置重试计数器
        
    def retry_request(self):
        """重试请求"""
        size_choice = self.size_combo.currentText()
        if size_choice == "小":
            size_param = "?imageMogr2/auto-orient/thumbnail/600x/blur/1x0/quality/75"
        elif size_choice == "中":
            size_param = "?imageMogr2/auto-orient/thumbnail/1000x/blur/1x0/quality/75"
        elif size_choice == "大":
            size_param = "?imageMogr2/auto-orient/blur/1x0/quality/71"
        else:  # 原始
            size_param = ""
        
        url = f"https://infinitypro-img.infinitynewtab.com/wallpaper/{self.current_category}/{self.current_code}.jpg{size_param}"
        request = QtNetwork.QNetworkRequest(QtCore.QUrl(url))
        self.reply = self.net_manager.get(request)
        self.reply.finished.connect(self.on_image_loaded)
        
    def download_wallpaper(self):
        """异步下载当前壁纸"""
        if not hasattr(self, 'current_category') or not hasattr(self, 'current_code'):
            QtWidgets.QMessageBox.warning(self, "警告", "请先获取一张壁纸！")
            return
            
        # 获取选中的尺寸
        selected_sizes = [size for size, cb in self.size_checks.items() if cb.isChecked()]
        if not selected_sizes:
            QtWidgets.QMessageBox.warning(self, "警告", "请至少选择一个尺寸！")
            return
            
        # 添加保存目录到实例变量
        self.save_dir = "wallpaper"
        os.makedirs(self.save_dir, exist_ok=True)
        
        # 添加reply引用保持
        self.active_replies = []  # 新增实例变量
        
        # 尺寸参数映射
        size_params = {
            "小": "?imageMogr2/auto-orient/thumbnail/600x/blur/1x0/quality/75",
            "中": "?imageMogr2/auto-orient/thumbnail/1000x/blur/1x0/quality/75",
            "大": "?imageMogr2/auto-orient/blur/1x0/quality/71",
            "原始": ""
        }
        
        # 下载所有选中尺寸
        self.download_counter = 0  # 添加下载计数器
        self.total_downloads = len(selected_sizes)  # 总下载任务数
        
        for size in selected_sizes:
            url = f"https://infinitypro-img.infinitynewtab.com/wallpaper/{self.current_category}/{self.current_code}.jpg{size_params[size]}"
            
            request = QtNetwork.QNetworkRequest(QtCore.QUrl(url))
            reply = self.net_manager.get(request)
            self.active_replies.append(reply)  # 保持引用
            reply.finished.connect(lambda r=reply, s=size: self.on_download_finished(r, s))

    def on_download_finished(self, reply, size):
        """单个下载完成回调"""
        self.download_counter += 1
        
        if reply.error():
            print(f"{size} 下载失败")
        else:
            # 保存文件
            img_data = reply.readAll()
            image = QtGui.QImage()
            if image.loadFromData(img_data):
                filename = f"{self.current_category}_{self.current_code}_{size}.jpg"
                # 使用实例变量中的保存路径
                image.save(os.path.join(self.save_dir, filename), "JPG")
                print(f"{size} 下载完成")
        
        # 移除已完成的reply
        if reply in self.active_replies:
            self.active_replies.remove(reply)
        
        # 全部下载完成时提示
        if self.download_counter == self.total_downloads:
            self.display_label.setText("所有图片已保存至wallpaper目录！")
            # 可选：重置计数器
            self.download_counter = 0
            self.total_downloads = 0

    def get_image_url(self, category):
        """生成指定分类的图片URL"""
        base_url = "https://infinitypro-img.infinitynewtab.com/wallpaper/"
        size_param = self.size_combo.currentText()
        return f"{base_url}{category}/7673.jpg{size_param}"

    def load_stylesheet(self, filename):
        """加载QSS样式表"""
        try:
            base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
            style_path = os.path.join(base_path, filename)
            print(f"尝试加载样式表: {style_path}")  # 添加调试信息
            if not os.path.exists(style_path):
                QtWidgets.QMessageBox.warning(self, "警告", f"样式表文件 {style_path} 未找到！")
                return
            with open(style_path, "r", encoding="utf-8") as f:
                self.setStyleSheet(f.read())
            print("样式表加载成功")  # 添加调试信息
        except Exception as e:
            print(f"加载样式表失败: {str(e)}")  # 添加调试信息
            QtWidgets.QMessageBox.warning(self, "错误", f"加载样式表失败: {str(e)}")

    def set_wallpaper(self):
        """设置当前图片为壁纸"""
        if not hasattr(self, 'current_image') or self.current_image.isNull():
            self.display_label.setText("没有可用的壁纸图片！")
            return

        try:
            # 保存临时文件
            temp_dir = tempfile.gettempdir()
            temp_path = os.path.join(temp_dir, "current_wallpaper.jpg")
            self.current_image.save(temp_path, "JPG")
            
            # Windows系统设置壁纸
            if sys.platform == 'win32':
                ctypes.windll.user32.SystemParametersInfoW(20, 0, temp_path, 3)
            # Linux系统（GNOME）
            elif sys.platform == 'linux':
                os.system(f"gsettings set org.gnome.desktop.background picture-uri file://{temp_path}")
            else:
                self.display_label.setText("当前系统不支持自动设置壁纸")
                return
                
            self.display_label.setText("壁纸设置成功！")
        except Exception as e:
            self.display_label.setText(f"设置壁纸失败：{str(e)}")

if __name__ == "__main__":
    try:
        print("程序启动中...")  # 添加调试信息
        app = QtWidgets.QApplication(sys.argv)
        print("QApplication创建成功")
        window = WallpaperApp()
        print("主窗口创建成功")
        window.show()
        print("主窗口显示成功")
        sys.exit(app.exec_())
    except Exception as e:
        print(f"程序启动失败: {str(e)}")  # 确保错误信息打印到控制台
        logging.exception("程序启动失败")
        QtWidgets.QMessageBox.critical(None, "错误", f"程序启动失败：{str(e)}")
